<template>
  <div class="groupby">
    <span>{{$t('custom.component.columns.dimension')}}</span>
    <el-popover ref="grounpbyForm"
                placement="top"
                width="280"
                @after-leave="handleLeaveGroupAddPopover"
                trigger="manual"
                v-model="addVisible"
                style="z-index:2019;display:block;float:right">
      <el-form ref="grounpbyElForm"
                class="groupby-popover"
               :rules="summarizebyFormRules"
               :model="newGroupBy">
        <el-form-item :label="$t('custom.component.columns.fields')"
                      prop="field">
          <el-select v-model="newGroupBy.field"
                     @change="newGroupByFieldChange"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="(item,index) in columnList"
                       :key="index"
                       :label="item.alias"
                       :value="item.columnName">
                <DataTypeIcon :dataTypeObj="{type:item.businessType,value:item.alias}"></DataTypeIcon>
                       </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.grouptype')"
                      v-if="typeGroupFlag">
          <el-select v-model="newGroupBy.groupType"
                     @change="newGroupByGroupTypeChange"
                    :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option :label="$t('custom.component.columns.date')"
                       value="date"></el-option>
            <el-option :label="$t('custom.component.columns.number')"
                       value="number"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.period')"
                      prop="period"
                      v-if="typeGroupFlag">
          <el-select v-model="newGroupBy.period"
                     :disabled="!newGroupBy.groupType"
                     @change="newGroupByPeriodChange"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="item in GroupByPeriod"
                       :key="item.label"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
                      prop="showbymonday"
                      v-if="typeGroupFlag&&(newGroupBy.dbType==='date'||newGroupBy.dbType==='datetime')&&newGroupBy.groupType==='date'&&newGroupBy.period==='weeks'">
          <el-checkbox v-model="newGroupBy.showbymonday">{{$t('custom.component.columns.showbymonday')}}</el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.alias')"
                      prop="alias">
          <el-input v-model="newGroupBy.alias"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.formatType')">
          <el-select class="formatType"
                     style="float:left"
                     @change="newGroupFormatChange"
                     v-model="newGroupBy.businessType"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="item in formatTypeListNew"
                       :key="item.id"
                       :label="item.dictLabel"
                       :value="item.dictValue">
                       <span>
                        <i :class="`cuifont ${item.subjectCode}`"></i>
                          </span>
                            <span style="margin-left: 10px">{{ item.dictLabel }}</span>
                       </el-option>
          </el-select>
          <el-popover ref="formatPopoverGroupby"
                      placement="right-end"
                      width="430"
                      height="211"
                      @opened="openedHandler"
                      @show="addorEditFormatShowGroupBy"
                      @hide="resetFormatTypeGroupBy"
                      trigger="click"
                      style="z-index:2019;display:block;">
              <h3>{{$t('custom.component.columns.format')}}</h3>
            <NumberFormat ref="NumberFormat" v-if="newGroupBy.businessType ==='number'" :formatDataInfo="newGroupBy"></NumberFormat>
            <div v-else-if="newGroupBy.businessType ==='hyperlinks'">
              <el-dropdown trigger="click" style="width: 100%;" @command="handleCommand">
                <span class="el-dropdown-link">
                  <el-input id="HyperlinkInput" @input="inputHander" :suffix-icon="!newGroupBy.fieldsFormat ?  'el-icon-arrow-down' : ''" clearable v-model="newGroupBy.fieldsFormat" style="width: 100%;" placeholder="Please Enter or Select"></el-input>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <div v-if="formatTypeItemListGroup.rootURL.length>0">
                    <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.rootURL')}}</span>
                    <el-tooltip class="item" :open-delay="1000" effect="dark" :content="its.subjectCode" placement="top" v-for="(its,index) in formatTypeItemListGroup.rootURL" :key="index">
                      <el-dropdown-item :command="its.dictLabel">{{its.dictLabel}}</el-dropdown-item>
                    </el-tooltip>
                    <el-divider></el-divider>
                  </div>
                  <div v-if="formatTypeItemListGroup.templateURL.length>0">
                    <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.templateURL')}}</span>
                    <el-dropdown-item :command="its.dictLabel" v-for="its in formatTypeItemListGroup.templateURL" :key="its.dictLabel">{{its.dictLabel}}</el-dropdown-item>
                    <el-divider></el-divider>
                  </div>
                  <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.datacolumnsplace')}}</span>
                  <el-dropdown-item :command="its.alias" v-for="its in formatTypeItemListGroup.dataColumns" :key="its.alias">{{its.alias}}</el-dropdown-item>
                  <el-dropdown-item :command="newGroupBy.alias">{{resetCol(newGroupBy.alias)}}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-checkbox style="margin-top:5px" v-model="newGroupBy.isNewPage">{{$t('custom.component.datasetsqlmodel.openCurrentPage')}}</el-checkbox>
            </div>
            <el-select v-model="newFieldsFormatGroupBy" v-else
                       clearable
                       filterable
                       default-first-option
                       :placeholder="$t('custom.component.columns.pleaseselect')"
                       style="width: 100%;">
              <el-option v-for="(its,index) in formatTypeItemListGroup"
                         :key="index"
                         :label="its.dictLabel"
                         :value="its.dictValue"></el-option>
            </el-select>
            <div class="pop_title">
              {{ $t('custom.component.columns.poptitle') }}</div>
            <div v-if="newGroupBy.businessType ==='datetime'">
                  <el-checkbox v-model="timezoneChecked">{{$t('custom.component.columns.timezone')}}</el-checkbox>
              </div>
            <div style="text-align: right; margin: 10px auto;">
              <el-button size="small"
                         @click="closeFormatPopoverGroupBy">{{ $t('custom.close') }}</el-button>
              <el-button size="small"
                         type="primary"
                         @click="saveFormatPopoverGroupby">{{ $t('custom.save') }}</el-button>
            </div>
            <div slot="reference">
              <el-image fit="cover"
                        style="float:right;margin-top:5px"
                        :src="$ossLink+'/app/dashboard/format.png'"></el-image>
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin: 10px auto;">
        <el-button size="mini"
                   @click="handleCloseGroupAddPopover">{{$t('notice.close')}}</el-button>
        <el-button size="mini"
                   type="primary"
                   @click="addGrounpBy">{{$t('add')}}</el-button>
      </div>
      <i slot="reference"
         class="cuifont icon_add"
         style="float:right;margin-right:5px" @click="handleOpenGroupAddPopover"></i>
    </el-popover>
    <ul class="summarize-list">
      <li v-for="(item,index) in dataInfoCopy.dimensions"
          :key="index"  :style="{backgroundColor:rowClass(item,index)}">{{item.alias}}
        <i class="el-icon-delete summarizeByDelete"
           @click="deleteGrounpBy(index)"></i>
        <el-popover ref="editGrounpByForm"
                    placement="top"
                    width="280"
                    @after-leave="handleLeaveGroupEditPopover"
                    trigger="manual"
                    v-model="item.editVisible"
                    style="z-index:2019;display:block;float:right">
          <el-form ref="groupByEditForm"
                    class="groupby-popover"
                   :rules="editFormRulesGroupBy"
                   :model="newGroupBy">
            <el-form-item :label="$t('custom.component.columns.fields')"
                          prop="field">
              <el-select v-model="newGroupBy.field"
                         @change="editNewGroupByFieldChange"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option v-for="(item,index) in columnList"
                           :key="index"
                           :label="item.alias"
                           :value="item.columnName">
                  <DataTypeIcon :dataTypeObj="{type:item.businessType,value:item.alias}"></DataTypeIcon>
                           </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.grouptype')"
                          v-if="typeGroupFlag"
                          prop="groupType">
              <el-select v-model="newGroupBy.groupType"
                         @change="editNewGroupByGroupTypeChange"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option :label="$t('custom.component.columns.date')"
                           value="date"></el-option>
                <el-option :label="$t('custom.component.columns.number')"
                           value="number"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.period')"
                          v-if="typeGroupFlag"
                          prop="period">
              <el-select v-model="newGroupBy.period"
                         :disabled="!newGroupBy.groupType"
                         :placeholder="$t('custom.component.columns.pleaseselect')"
                         @change="editNewGroupByPeriodChange">
                <el-option v-for="item in GroupByPeriod"
                           :key="item.label"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
                      prop="showbymonday"
                      v-if="typeGroupFlag&&(newGroupBy.dbType==='date'||newGroupBy.dbType==='datetime')&&newGroupBy.groupType==='date'&&newGroupBy.period==='weeks'">
          <el-checkbox v-model="newGroupBy.showbymonday">{{$t('custom.component.columns.showbymonday')}}</el-checkbox>
        </el-form-item>
            <el-form-item :label="$t('custom.component.columns.alias')"
                          prop="alias">
              <el-input v-model="newGroupBy.alias"></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.formatType')">
              <el-select class="formatType"
                         style="float:left"
                         :key="item.id"
                         @change="newGroupFormatChange"
                         v-model="newGroupBy.businessType"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option v-for="item in formatTypeListNewEdit(item,formatTypeList,newGroupBy.field)"
                           :key="item.id"
                           :label="item.dictLabel"
                           :value="item.dictValue">
                          <span>
                            <i :class="`cuifont ${item.subjectCode}`"></i>
                          </span>
                          <span style="margin-left: 10px">{{ item.dictLabel }}</span>
                           </el-option>
              </el-select>
              <el-popover ref="editFormatPopoverGroupby"
                          placement="right-end"
                          width="430"
                          height="211"
                          @opened="editOpenedHandler"
                          @hide="resetEditFormatTypeGroupBy"
                          @show="editFormatGroupBy"
                          trigger="click"
                          style="z-index:2019;display:block;">
              <h3>{{$t('custom.component.columns.format')}}</h3>
                <NumberFormat ref="NumberFormatEdit" v-if="newGroupBy.businessType ==='number'" :formatDataInfo="newGroupBy"></NumberFormat>
                <div v-else-if="newGroupBy.businessType ==='hyperlinks'">
                  <el-dropdown trigger="click" style="width: 100%;" @command="handleCommand">
                    <span class="el-dropdown-link">
                      <el-input id="HyperlinkInput" @input="inputHander" :suffix-icon="!newGroupBy.fieldsFormat ?  'el-icon-arrow-down' : ''" clearable v-model="newGroupBy.fieldsFormat" style="width: 100%;" placeholder="Please Enter or Select"></el-input>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <div v-if="formatTypeItemListGroup.rootURL.length>0">
                        <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.rootURL')}}</span>
                        <el-tooltip :open-delay="1000" class="item" effect="dark" :content="its.subjectCode" placement="top" v-for="(its,index) in formatTypeItemListGroup.rootURL" :key="index">
                          <el-dropdown-item :command="its.dictLabel">{{its.dictLabel}}</el-dropdown-item>
                        </el-tooltip>
                        <el-divider></el-divider>
                      </div>
                      <div v-if="formatTypeItemListGroup.templateURL.length>0">
                        <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.templateURL')}}</span>
                        <el-dropdown-item :command="its.dictLabel" v-for="its in formatTypeItemListGroup.templateURL" :key="its.dictLabel">{{its.dictLabel}}</el-dropdown-item>
                        <el-divider></el-divider>
                      </div>
                      <span class="dropDownTitle">{{$t('custom.component.datasetsqlmodel.datacolumnsplace')}}</span>
                      <el-dropdown-item :command="its.alias" v-for="its in formatTypeItemListGroup.dataColumns" :key="its.alias">{{its.alias}}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-checkbox style="margin-top:5px" v-model="newGroupBy.isNewPage">{{$t('custom.component.datasetsqlmodel.openCurrentPage')}}</el-checkbox>
                </div>
                <el-select v-model="newFieldsFormatGroupBy" v-else
                           clearable
                           filterable
                           default-first-option
                           :placeholder="$t('custom.component.columns.pleaseselect')"
                           style="width: 100%;">
                  <el-option v-for="(its,index) in formatTypeItemListGroup"
                             :key="index"
                             :label="its.dictLabel"
                             :value="its.dictValue"></el-option>
                </el-select>
                <div class="pop_title">{{$t('custom.component.columns.poptitle')}}</div>
                <div v-if="newGroupBy.businessType ==='datetime'">
                  <el-checkbox v-model="timezoneChecked">{{$t('custom.component.columns.timezone')}}</el-checkbox>
                </div>
                
                <div style="text-align: right; margin: 10px auto;">
                  <el-button size="small"
                             @click="closeEditFormatGroupBy">{{ $t('custom.close') }}</el-button>
                  <el-button size="small"
                             type="primary"
                             @click="saveEditFormatPopoverGroupby">{{ $t('custom.save') }}</el-button>
                </div>
                <div slot="reference">
                  <el-image fit="cover"
                            style="float:right;margin-top:5px"
                            :src="$ossLink+'/app/dashboard/format.png'"></el-image>
                </div>
              </el-popover>
            </el-form-item>
          </el-form>
          <div style="text-align: right; margin: 10px auto;">
            <el-button size="mini"
                       @click="handleCloseGroupEditPopover">{{$t('notice.close')}}</el-button>
            <el-button size="mini"
                       type="primary"
                       @click="confirmGrounpby">{{$t('confirm')}}</el-button>
          </div>
          <i slot="reference"
             class="el-icon-edit summarizeByEidt"
             @click.stop="handleOpenGroupEditPopover(item,index)"
             style="float:right;line-height:35px;margin-right:10px"></i>
        </el-popover>
      </li>
    </ul>
  </div>
</template>

<script>
import DataTypeIcon from '@/components/script-render/components/data-type-icon'
import NumberFormat from '@/components/columns/columns-numberformat.vue'
import { isIncludeDot } from '@/utils/validate'
export default {
  components: { DataTypeIcon, NumberFormat },
  props: {
    // eslint-disable-next-line vue/no-dupe-keys
    dataInfoCopy: {
      type: Object,
      default: function () {
        return {}
      }
    },
    dataInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    columnList: {
      type: Array,
      default: function () {
        return []
      }
    },
    errorFieldsList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    var validateEdit = (rule, value, callback) => {
      if (!Array.isArray(this.dataInfoCopy.measures)) {
        this.dataInfoCopy.measures = []
      }
      let resIndex = ''
      let concatIndex = ''
      if (this.SummarizeByEditIndex.toString()) {
        resIndex = this.dataInfoCopy.measures.findIndex(item => {
          return item.alias === this.newSummarizeBy.alias
        })
      }
      if (this.GrounpByEditIndex.toString()) {
        resIndex = this.dataInfoCopy.dimensions.findIndex(item => {
          return item.alias === this.newGroupBy.alias
        })
      }
      concatIndex = this.dataInfoCopy.dimensions.concat(this.dataInfoCopy.measures).findIndex(item => {
        return (item.alias === this.newGroupBy.alias || item.alias === this.newSummarizeBy.alias)
      })
      if (concatIndex !== -1 && ((this.SummarizeByEditIndex.toString() && resIndex !== this.SummarizeByEditIndex) || (this.GrounpByEditIndex.toString() && resIndex !== this.GrounpByEditIndex))) {
        return callback(new Error(this.$t('custom.component.columns.aliasalreadyexist')))
      } else {
        callback()
      }
    }
    var validateAlias = (rule, value, callback) => {
      if (!Array.isArray(this.dataInfoCopy.measures)) {
        this.dataInfoCopy.measures = []
      }
      if (!Array.isArray(this.dataInfoCopy.dimensions)) {
        this.dataInfoCopy.dimensions = []
      }
      let isExist = this.dataInfoCopy.measures.concat(this.dataInfoCopy.dimensions).some(item => {
        return (item.alias === this.newSummarizeBy.alias || item.alias === this.newGroupBy.alias)
      })
      if (isExist) {
        return callback(new Error(this.$t('custom.component.columns.aliasalreadyexist')))
      } else {
        callback()
      }
    }
    return {
      storageDeleteDataSetHead: '',
      GrounpByEditIndex: '',
      typeGroupFlag: false,
      GroupByPeriod: [],
      loading: true,
      modelId: null,
      fieldsList: [],
      // groupFieldsList: [],
      fieldsLoading: false,
      allDataList: [],
      selectGroupList: [],
      // saveSource: '',
      isNameOk: true,
      isNew: true,
      gadgetId: '',
      newSummarizeBy: {
        func: '',
        alias: '',
        field: '',
        businessType: '',
        fieldsFormat: '',
        distinct: false,
        advanced: false,
        fx: ''
      },
      newGroupBy: {
        alias: '',
        field: '',
        fieldAlias: '',
        fieldsFormat: '',
        fieldsNewFormat: {
          fieldsNewFormatType: 'number',
          decimals: 0,
          option: 'regular'
        },
        showbymonday: false,
        dbType: '',
        editVisible: false
      },
      newFieldsFormat: '',
      newFieldsFormatGroupBy: '',
      timezoneChecked: true,
      SummarizeByEditIndex: '',
      summarizebyFormRules: {
        field: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        period: [
          { validator: this.validateNewPeriod, trigger: 'change' }
          // { required: true, message: 'please select', trigger: 'change' }
        ],
        alias: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { required: true, message: this.$t('custom.component.columns.inputalias'), trigger: 'blur' },
          { validator: validateAlias, trigger: 'change' }
        ]
      },
      editFormRulesGroupBy: {
        field: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        alias: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { required: true, message: this.$t('custom.component.columns.inputalias'), trigger: 'blur' },
          { validator: validateEdit, trigger: 'change' }
        ],
        groupType: [
          { validator: this.validateEditGroupType, trigger: 'change' }
          // { required: true, message: 'please select', trigger: 'change' }
        ],
        period: [
          { validator: this.validateEditPeriod, trigger: 'change' }
          // { required: true, message: 'please select', trigger: 'change' }
        ]
      },
      addVisible: false,
      formatTypeListNew:[]
    }
  },
  computed: {
    formatTypeItemListGroup () {
      let temp = []
      switch (this.newGroupBy.businessType) {
        case 'date':
          temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_date').dataList
          break
        case 'datetime':
          temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_datetime').dataList
          break
        case 'text':
          temp = []
          break
        case 'boolean':
          temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_boolean').dataList
          break
        case 'currency':
          temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_currency').dataList
          break
        case 'number':
          temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_number').dataList
          break
        case 'hyperlinks':
          var _self = this
          temp.rootURL = JSON.parse(JSON.stringify(window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_hyperlinks_two').dataList))
          temp.rootURL.forEach((item) => {
            item.dictLabel = `{${item.dictLabel}}`
            item.subjectCode = _self.$store.state.user[item.subjectCode]
          })
          temp.rootURL = temp.rootURL.filter(item => {
            return !!item.subjectCode === true
          })
          temp.templateURL = JSON.parse(JSON.stringify(window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_hyperlinks').dataList))
          temp.templateURL.forEach(item => {
            item.subjectCode = _self.$store.state.user[item.subjectCode]
          })
          temp.templateURL = temp.templateURL.filter(item => {
            return !!item.subjectCode === true
          })
          temp.dataColumns = JSON.parse(JSON.stringify(this.dataInfoCopy.dimensions))
          temp.dataColumns.forEach(item => {
            item.alias = `{${item.alias}}`
          })
          break
        default:
          break
      }
      return temp
    },
    formatTypeList () {
      var temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list').dataList
      if (this.dataInfo.gadgetType !== 'gridgadget') {
        temp = temp.filter(item => item.dictLabel !== 'Hyperlinks')
      }
      return temp
    }
  },
  watch: {
    'columnList': {
      handler (val) {
        try {
          this.dataInfoCopy.dimensions.forEach(item => {
            var result = val.find(i => i.columnName === item.field)
            item.fieldAlias = result.alias
          })
          var res = val.find(item => item.columnName === this.newGroupBy.field)
          this.newGroupBy.fieldAlias = res.alias
          // this.columnList = JSON.parse(JSON.stringify(val))
          this.columnList.forEach((item, index) => {
            if (!item.alias || item.alias.trim() === '') {
              this.columnList.splice(index, 1)
            }
          })
        } catch (error) {
          return []
        }
      },
      deep: true
    },
    newGroupBy: {
      handler (val) {
        if (val.field) {
          var res = this.columnList.find(item => item.columnName === val.field)
          val.fieldAlias = res.alias
        }
      },
      deep: true
    },
    'dataInfoCopy.dimensions': {
      handler (val) {
        try {
          val.forEach(item => {
            if (this.errorFieldsList && this.errorFieldsList.length > 0) {
              let findIndex = this.errorFieldsList.findIndex(e => e.columnName === item.field && e.refLocation === 'widgetBuild_dataset_measure')
              if (findIndex > -1) {
                item.fieldStatus = true
              }
            }
          })
        } catch (error) {
          return []
        }
      },
      immediate: true,
      deep: true
    }

  },
  created () {
  },
  methods: {
    formatTypeListNewEdit(item,formatTypeList,field){
      let formatTypeListNew =[]
      let fieldObj = field&&this.columnList.find(item=>item.columnName===field)
     if(fieldObj&&fieldObj.dbType&&fieldObj.dbType==='datetime') {
      formatTypeListNew = formatTypeList.filter(item=>item.dictValue!=='date')
     } else if(fieldObj&&fieldObj.dbType&&fieldObj.dbType==='date') {
        formatTypeListNew = formatTypeList.filter(item=>item.dictValue!=='datetime')
     } else {
      formatTypeListNew = formatTypeList
     }
      return formatTypeListNew
    },
    rowClass (row, index) {
      if (row.fieldStatus) {
        return '#FEF0F0'
      }
    },
    resetCol (val) {
      return `{${val}}`
    },
    inputHander () {
      this.$forceUpdate()
    },
    handleCommand (command) {
      if (command === 'ConnectWise Ticket URL' || command === 'ConnectWise TimeEntry URL' || command === 'AutoTask Ticket URL') {
        this.newGroupBy.fieldsFormat = command
      } else {
        if (!this.newGroupBy.fieldsFormat) {
          this.newGroupBy.fieldsFormat = ''
        }
        this.newGroupBy.fieldsFormat += command
      }
      this.$forceUpdate()
    },
    openedHandler () {
      if (this.$refs.NumberFormat) {
        this.$refs.NumberFormat.open()
      }
    },
    editOpenedHandler () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.GrounpByEditIndex]) {
        this.$refs.NumberFormatEdit[this.GrounpByEditIndex].open()
      }
    },
    inputHandler () {
      this.$forceUpdate()
    },
    returnGroupby () {
      try {
        return this.dataInfoCopy.dimensions
      } catch (error) {
        return []
      }
    },
    addorEditFormatShowGroupBy () {
      if (this.$refs.NumberFormat) {
        this.$refs.NumberFormat.open()
      }
      this.newFieldsFormatGroupBy = this.newGroupBy.fieldsFormat
    },
    newGroupFormatChange () {
      this.newGroupBy.fieldsFormat = ''
      this.newFieldsFormatGroupBy = ''
      this.timezoneChecked = true
      this.newGroupBy.fieldsNewFormat = {
        fieldsNewFormatType: 'number',
        decimals: 0,
        option: 'regular'
      }
      if (this.newGroupBy.businessType === 'datetime') {
        this.newGroupBy.fieldsFormat = 'YYYY-MM-DD HH:mm'
      } else if (this.newGroupBy.businessType === 'date') {
        this.newGroupBy.fieldsFormat = 'YYYY-MM-DD'
      }
      this.closeEditFormatGroupBy()
      this.closeFormatGroupBy()
    },
    closeEditFormatGroupBy () {
      if (this.$refs.editFormatPopoverGroupby && this.$refs.editFormatPopoverGroupby[this.GrounpByEditIndex]) {
        this.$refs.editFormatPopoverGroupby[this.GrounpByEditIndex].doClose()
      }
      // if (this.$refs.formatPopoverGroupby) {
      //   this.$refs.formatPopoverGroupby.doClose()
      // }
    },
    closeFormatGroupBy () {
      if (this.$refs.formatPopoverGroupby) {
        this.$refs.formatPopoverGroupby.doClose()
      }
    },
    editFormatGroupBy () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.GrounpByEditIndex]) {
        this.$refs.NumberFormatEdit[this.GrounpByEditIndex].open()
      }
      this.newFieldsFormatGroupBy = this.newGroupBy.fieldsFormat
      this.timezoneChecked = this.newGroupBy.timezoneChecked
    },
    resetFormatType () {
      this.$refs.formatPopover.doClose()
      this.newFieldsFormat = ''
    },
    resetFormatTypeGroupBy () {
      this.$refs.formatPopoverGroupby.doClose()
      this.newFieldsFormatGroupBy = ''
      this.timezoneChecked = true
    },
    resetEditFormatTypeGroupBy () {
      if (this.$refs.editFormatPopoverGroupby) this.$refs.editFormatPopoverGroupby[this.GrounpByEditIndex].doClose()
      this.newFieldsFormatGroupBy = ''
      this.timezoneChecked = true
    },
    closeFormatPopoverGroupBy () {
      this.$refs.formatPopoverGroupby.doClose()
      this.resetFormatTypeGroupBy()
    },

    // TIP Optimization and handling pop-ups are not closed
    handleCloseGroupEditPopover () {
      if (this.GrounpByEditIndex !== '') {
        this.dataInfoCopy.dimensions[this.GrounpByEditIndex].editVisible = false
        this.GrounpByEditIndex = ''
        this.newGroupBy = {
          alias: '',
          field: '',
          fieldAlias: '',
          businessType: '',
          showbymonday: false,
          fieldsNewFormat: {
            fieldsNewFormatType: 'number',
            decimals: 0,
            option: 'regular'
          },
          dbType: ''
        }
      }
    },
    handleOpenGroupEditPopover (item, index) {
      if (this.$refs['groupByEditForm'][this.GrounpByEditIndex]) {
        this.$refs['groupByEditForm'][this.GrounpByEditIndex].clearValidate()
      }
      this.handleCloseGroupEditPopover()
      this.handleCloseGroupAddPopover()

      this.newGroupBy = { ...JSON.parse(JSON.stringify(item)), editVisible: true }
      this.editEveryGroupByInitForm(item.field)
      if (item.groupType) this.editEveryGroupByInitFormPeirod(item.groupType, index)
      this.updateReportColumn()

      this.GrounpByEditIndex = index

      this.dataInfoCopy.dimensions[this.GrounpByEditIndex].editVisible = true
    },
    handleLeaveGroupEditPopover () {
      if (this.$refs['groupByEditForm'][this.GrounpByEditIndex]) {
        this.$refs['groupByEditForm'][this.GrounpByEditIndex].clearValidate()
      }
    },
    handleLeaveGroupAddPopover () {
      if (this.$refs['grounpbyElForm']) {
        this.$refs['grounpbyElForm'].clearValidate()
      }
    },
    closeGroupby () {
      this.handleCloseGroupEditPopover()
      this.handleCloseGroupAddPopover()
    },
    handleOpenGroupAddPopover () {
      if (this.$refs['grounpbyElForm']) {
        this.$refs['grounpbyElForm'].clearValidate()
      }
      this.handleCloseGroupEditPopover()
      this.handleCloseGroupAddPopover()

      this.addVisible = true
    },
    handleCloseGroupAddPopover () {
      if (this.addVisible) {
        this.typeGroupFlag = false

        this.GroupByPeriod = []
        this.newGroupBy = {
          alias: '',
          field: '',
          fieldAlias: '',
          businessType: '',
          showbymonday: false,
          fieldsNewFormat: {
            fieldsNewFormatType: 'number',
            decimals: 0,
            option: 'regular'
          },
          dbType: ''
        }
        this.addVisible = false
      }
    },

    saveEditFormatPopoverGroupby () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.GrounpByEditIndex]) {
        this.newGroupBy.fieldsNewFormat = this.$refs.NumberFormatEdit[this.GrounpByEditIndex].save().fieldsNewFormat
      }
      if (this.newGroupBy.businessType !== 'hyperlinks') {
        this.newGroupBy.fieldsFormat = this.newFieldsFormatGroupBy
        this.newGroupBy.timezoneChecked = this.timezoneChecked
      }
      this.$refs.editFormatPopoverGroupby[this.GrounpByEditIndex].doClose()
      this.$refs.formatPopoverGroupby.doClose()
    },
    saveFormatPopoverGroupby () {
      if (this.$refs.NumberFormat) {
        var formatDataInfo = this.$refs.NumberFormat.save()
        this.newGroupBy.fieldsNewFormat = formatDataInfo.fieldsNewFormat
      }
      if (this.newGroupBy.businessType !== 'hyperlinks') {
        this.newGroupBy.fieldsFormat = this.newFieldsFormatGroupBy
        this.newGroupBy.timezoneChecked = this.timezoneChecked
      }
      this.$refs.formatPopoverGroupby.doClose()
    },
    validateEditGroupType (rule, value, callback) {
      if (this.newGroupBy.period && !this.newGroupBy.groupType) {
        return callback(new Error(this.$t('custom.component.columns.pleaseselect')))
      } else {
        callback()
      }
    },
    validateNewPeriod (rule, value, callback) {
      if (this.newGroupBy.groupType && !this.newGroupBy.period) {
        return callback(new Error(this.$t('custom.component.columns.pleaseselect')))
      } else {
        callback()
      }
    },
    validateEditPeriod (rule, value, callback) {
      if (this.newGroupBy.groupType && !this.newGroupBy.period) {
        return callback(new Error(this.$t('custom.component.columns.pleaseselect')))
      } else {
        callback()
      }
    },

    deleteGrounpBy (val) {
      this.dataInfoCopy.dimensions.splice(val, 1)
      this.$emit('setOrderbyList')
      this.$forceUpdate()
      this.updateReportColumn()
    },

    addGrounpBy () {
      if (isIncludeDot(this.newGroupBy.alias)) {
        return this.$message.error(this.$t('validate.isIncludeDot'))
      }
      this.$refs['grounpbyElForm'].validate(isPass => {
        var _self = this
        if (isPass) {
          if (!Array.isArray(this.dataInfoCopy.dimensions)) {
            _self.dataInfoCopy.dimensions = []
          }
          _self.dataInfoCopy.dimensions.push(JSON.parse(JSON.stringify(_self.newGroupBy)))
          // _self.updateReportColumn()
          _self.handleCloseGroupAddPopover()
          _self.$emit('setOrderbyList')
        }
      })
    },
    confirmGrounpby () {
      if (isIncludeDot(this.newGroupBy.alias)) {
        return this.$message.error(this.$t('validate.isIncludeDot'))
      }
      this.$refs['groupByEditForm'][this.GrounpByEditIndex].validate(isPass => {
        if (isPass) {
          this.dataInfoCopy.dimensions[this.GrounpByEditIndex] = JSON.parse(JSON.stringify(this.newGroupBy))
          this.updateReportColumn()
          this.handleCloseGroupEditPopover()
          this.$emit('setOrderbyList')
        }
      })
    },
    newGroupByFieldChange (val) {
      this.newGroupBy.showbymonday = false
      this.typeGroupFlag = false
      this.GroupByPeriod = []
      this.columnList.forEach(element => {
        if (val === element.columnName && (element.businessType === 'datetime' || element.businessType === 'date')) this.typeGroupFlag = true
      })
      if (this.typeGroupFlag) {
        this.newGroupBy.groupType = ''
        this.newGroupBy.period = ''
        this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field
        // this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
      } else {
        delete this.newGroupBy.groupType
        delete this.newGroupBy.period
        this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field
      }
      if (this.newGroupBy.businessType) {
        this.newGroupBy.businessType = ''
        this.newGroupBy.fieldsFormat = ''
        this.newGroupBy.fieldsNewFormat = {
          fieldsNewFormatType: 'number',
          decimals: 0,
          option: 'regular'
        }
      }
      let result = this.columnList.find(item => {
        return item.columnName === this.newGroupBy.field
      })
      this.newGroupBy.dbType = result ? result.dbType : ''
      if (this.newGroupBy.dbType&&this.newGroupBy.dbType==='date') {
        this.formatTypeListNew = this.formatTypeList.filter(item=>item.dictValue!=='datetime')
      } else if (this.newGroupBy.dbType&&this.newGroupBy.dbType==='datetime') {
        this.formatTypeListNew = this.formatTypeList.filter(item=>item.dictValue!=='date')
      } else {
        this.formatTypeListNew = this.formatTypeList
      }    
      this.closeFormatGroupBy()
    },
    editEveryGroupByInitForm (val) {
      this.columnList.forEach(element => {
        if (val === element.columnName && (element.businessType === 'datetime' || element.businessType === 'date')) this.typeGroupFlag = true
      })
    },
    editNewGroupByFieldChange (val) {
      this.newGroupBy.showbymonday = false
      this.closeEditFormatGroupBy()
      this.GroupByPeriod = []
      this.typeGroupFlag = false
      this.editEveryGroupByInitForm(val)
      if (this.typeGroupFlag) {
        this.newGroupBy.groupType = ''
        this.newGroupBy.showbymonday = false
        this.newGroupBy.period = ''
        this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field
        // this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
      } else {
        delete this.newGroupBy.groupType
        delete this.newGroupBy.period
        this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field
      }
      if (this.newGroupBy.businessType) {
        this.newGroupBy.businessType = ''
        this.newGroupBy.showbymonday = false
        this.newGroupBy.fieldsFormat = ''
        this.newGroupBy.fieldsNewFormat = {
          fieldsNewFormatType: 'number',
          decimals: 0,
          option: 'regular'
        }
      }
      let result = this.columnList.find(item => {
        return item.columnName === this.newGroupBy.field
      })
      this.newGroupBy.dbType = result ? result.dbType : ''
    },
    editEveryGroupByInitFormPeirod (val) {
      if (val === 'date') {
        this.GroupByPeriod = [
          {
            label: 'Hours',
            value: 'hours'
          },
          {
            label: 'Days',
            value: 'days'
          },
          {
            label: 'Weeks',
            value: 'weeks'
          },
          {
            label: 'Weeks(Sun-Sat)',
            value: 'weeks(sun-sat)'
          },
          {
            label: 'Weeks(Sat-Fri)',
            value: 'weeks(sat-fri)'
          },
          {
            label: 'Months',
            value: 'months'
          },
          {
            label: 'Quarter',
            value: 'quarter'
          },
          {
            label: 'Years',
            value: 'years'
          }
        ]
      } else if (val === 'number') {
        this.GroupByPeriod = [
          {
            label: 'Hours',
            value: 'hours'
          },
          {
            label: 'Days',
            value: 'days'
          },
          {
            label: 'WeekDay',
            value: 'weekday'
          },
          {
            label: 'Weeks',
            value: 'weeks'
          },
          {
            label: 'Months',
            value: 'months'
          },
          {
            label: 'Years',
            value: 'years'
          }
        ]
      }
    },
    editNewGroupByGroupTypeChange (val) {
      this.newGroupBy.showbymonday = false
      this.closeEditFormatGroupBy()
      this.newGroupBy.period = ''
      this.editEveryGroupByInitFormPeirod(val)
      this.$forceUpdate()
    },
    editNewGroupByPeriodChange (val) {
      this.newGroupBy.showbymonday = false
      this.closeEditFormatGroupBy()
      // this.newGroupBy.period = val
      if (this.newGroupBy.groupType && this.newGroupBy.period) this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field + '_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
      this.$forceUpdate()
    },
    newGroupByPeriodChange (val) {
      this.newGroupBy.showbymonday = false
      this.closeFormatGroupBy()
      if (this.newGroupBy.groupType && this.newGroupBy.period) this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field + '_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
    },
    newGroupByGroupTypeChange (val) {
      this.newGroupBy.showbymonday = false
      this.closeFormatGroupBy()
      this.newGroupBy.period = ''
      if (val === 'date') {
        if (this.newGroupBy.groupType && this.newGroupBy.period) this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field + '_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
        this.GroupByPeriod = [
          {
            label: 'Hours',
            value: 'hours'
          },
          {
            label: 'Days',
            value: 'days'
          },
          {
            label: 'Weeks',
            value: 'weeks'
          },
          {
            label: 'Weeks(Sun-Sat)',
            value: 'weeks(sun-sat)'
          },
          {
            label: 'Weeks(Sat-Fri)',
            value: 'weeks(sat-fri)'
          },
          {
            label: 'Months',
            value: 'months'
          },
          {
            label: 'Quarter',
            value: 'quarter'
          },
          {
            label: 'Years',
            value: 'years'
          }
        ]
      } else if (val === 'number') {
        if (this.newGroupBy.groupType && this.newGroupBy.period) this.newGroupBy.alias = 'groupBy_' + this.newGroupBy.field + '_' + this.newGroupBy.groupType + '_' + this.newGroupBy.period
        this.GroupByPeriod = [
          {
            label: 'Hours',
            value: 'hours'
          },
          {
            label: 'Days',
            value: 'days'
          },
          {
            label: 'WeekDay',
            value: 'weekday'
          },
          {
            label: 'Weeks',
            value: 'weeks'
          },
          {
            label: 'Months',
            value: 'months'
          },
          {
            label: 'Years',
            value: 'years'
          }
        ]
      }
    },
    updateReportColumn () {
      try {
        if (this.gadgetSetting.report === undefined || this.gadgetSetting.report.columns === undefined) {
          this.gadgetSetting.report = {}
        }
        this.gadgetSetting.report.columns = []
        this.dataInfoCopy.measures.forEach(item => this.pushColumn(item.alias))
        this.dataInfoCopy.dimensions.forEach(item => this.pushColumn(item.field))
        let tempList = []
        if (this.gadgetSetting.report !== undefined && this.gadgetSetting.report.columns) {
          tempList = this.gadgetSetting.report.columns.map(item => item.field)
        }
        this.$refs['gadget-setting'].resetData(tempList)
      } catch (error) { }
    },
    onGroupChange (val) {
      this.selectGroupList = val
      this.updateReportColumn()
    },
    clearGroupBy () {
      this.dataInfoCopy.dimensions = []
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped lang="scss">
.section-setting {
  height: 60vh;
  overflow: auto;
  word-break: normal;
}

.section-preview {
  background-color: #f5f5f5;
  height: 60vh;
  padding: 20px;
  overflow: auto;
}

.el-icon {
  width: 24px;
  height: 24px;
}

.el-icon:hover {
  box-shadow: 0 0 2px 1px;
}
.tabs-pane-padding {
  padding: 0px 15px !important;
}
.info-tips {
  font-size: 12px;
  color: #000000;
  opacity: 0.5;
  word-break: break-all;
}
.el-data-default-datasetLimit {
  ::v-deep .el-input--default {
    input {
      height: auto;
      line-height: unset;
    }
  }
}
.dropDownTitle {
  display: block;
  height: 36px;
  line-height: 36px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.5);
}
.el-dropdown-menu {
  width: 400px;
  max-height: 250px;
  overflow-y: scroll;
  padding: 20px;
}

.pop_title{
  word-break: keep-all;
  text-align: left;
}
</style>
<style lang="scss">
.groupby,.summarizeby {
  .dataset-order-by {
    .sort {
      cursor: pointer;
      padding: 2px;
      margin-right: 4px;
      &:hover {
        border-radius: 50%;
        background: #17b3a3;
        color: #ffffff;
      }
    }
    .el-button--mini.is-circle {
      padding: 5px;
    }
    .el-tag {
      height: 24px;
      line-height: 24px;
      margin-right: 6px;
    }
    .el-data-default {
      padding: 0px !important;
      margin-top: 10px !important;
      margin-bottom: 10px !important;
      line-height: 20px !important;
      .el-data-default-datasetLimit {
        ::v-deep .el-input--default {
          input {
            height: auto;
            line-height: unset;
          }
        }
      }
    }
  }
  .el-form--label-top ::v-deep .el-form-item__label {
    padding: 0px !important;
  }
  .el-form-item {
    margin-bottom: 10px !important;
  }
  .el-input__suffix {
    height: 32px !important;
  }
  .el-cascader-panel .el-checkbox {
    width: 100%;
    height: 100%;
    z-index: 10;
    position: absolute;
    top: 0px;
    right: 10px;
  }

  .el-dialog__body {
    overflow: auto;
  }
  #dataInfoCopy.summarizeBy {
    position: relative;
    .el-dialog {
      position: absolute;
      left: 0;
      bottom: 0;
    }
  }
  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  li {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .summarize-list li {
    height: 35px;
    background-color: #fff;
    border-radius: 5px;
    border: 1px solid #f0f0f0;
    margin: 5px 0;
    padding: 0 5px;
  }
  .summarizeByDelete {
    float: right;
    line-height: 35px !important;
    &:hover {
      cursor: pointer;
    }
  }
  .summarizeByEidt {
    float: right;
    line-height: 35px !important;
    margin-right: 10px;
    &:hover {
      cursor: pointer;
    }
  }
  .el-popover .el-select {
    width: 254px;
  }
  .el-divider {
    margin: 20px 0 15px !important;
  }
  .formatType.el-select {
    width: 85%;
  }
  .queryModelDialog .el-dialog__body {
    padding-left: 0 !important;
  }
  #tab-first {
    box-shadow: 0px 0px 0px #fff !important;
  }
  #tabsList .is-active {
    background-color: rgba(230, 247, 255, 1) !important;
  }
}
.groupby-popover {
  .el-form-item {
    margin-bottom: 10px !important;
  }
}
</style>
